/*****************************************************************
    Copyright (c) 2009 Julian M Bucknall

    Permission is hereby granted, free of charge, to any person
    obtaining a copy of this software and associated documentation
    files (the "Software"), to deal in the Software without
    restriction, including without limitation the rights to use,
    copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following
    conditions:

    The above copyright notice and this permission notice shall be
    included in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
    OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
    HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
    WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
    OTHER DEALINGS IN THE SOFTWARE.
******************************************************************/
using System;
using Graffiti.Core;
using System.Web;

namespace JmbCalendar {

  [Chalk("JmbCalendarHelper")]
  public class JmbCalendarHelper {
    const string archiveQuery = "archiveQuery";
    const string archiveWhere = "archive";

    public static string Pager(string cssClass, string prevText, string nextText) {
      GraffitiContext gc = GraffitiContext.Current;
      return Util.Pager(gc.PageIndex, gc.PageSize, gc.TotalRecords, cssClass, (string)gc[archiveQuery], prevText, nextText);
    }

    private static GraffitiContext GetContext(PostCollection posts) {
      GraffitiContext gc = GraffitiContext.Current;
      HttpRequest request = (HttpRequest)gc["request"];
      if (request != null)
        gc.PageIndex = int.Parse(request.QueryString["p"] ?? "1");
      gc.PageSize = SiteSettings.Get().PageSize;
      gc.TotalRecords = posts.Count;
      gc["where"] = archiveWhere;
      return gc;
    }

    private static PostCollection GetPageOfPosts(PostCollection posts, GraffitiContext gc) {
      int start = (gc.PageIndex - 1) * gc.PageSize;
      int end = start + gc.PageSize;
      if (end > gc.TotalRecords) end = gc.TotalRecords;

      PostCollection postsPage = new PostCollection();
      for (int i = start; i < end; i++) {
        postsPage.Add(posts[i]);
      }
      return postsPage;
    }

    public PostCollection GetPostsForMonth(string yearAsString, string monthAsString) {
      int year, month;
      GetDateParts(yearAsString, monthAsString, out year, out month);
      PostCollection posts = PostsReader.GetFilteredPostsForMonth(year, month);

      GraffitiContext gc = GetContext(posts);
      gc["title"] = "Archives for " + new DateTime(year, month, 1).ToString("MMMM yyyy") + " : " + SiteSettings.Get().Title;
      gc[archiveQuery] = string.Format("?year={0}&amp;month={1}", year, month);

      return GetPageOfPosts(posts, gc);
    }

    public PostCollection GetPostsForDay(string yearAsString, string monthAsString, string dayAsString) {
      int year, month, day;
      GetDateParts(yearAsString, monthAsString, dayAsString, out year, out month, out day);
      PostCollection posts = PostsReader.GetFilteredPostsForDate(year, month, day);

      GraffitiContext gc = GetContext(posts);
      gc["title"] = "Archives for " + new DateTime(year, month, day).ToShortDateString() + " : " + SiteSettings.Get().Title;
      gc[archiveQuery] = string.Format("?year={0}&amp;month={1}&amp;day={2}", year, month, day);

      return GetPageOfPosts(posts, gc);
    }

    public string GetMonthDisplayName(string yearAsString, string monthAsString) {
      int year, month;
      GetDateParts(yearAsString, monthAsString, out year, out month);
      return new DateTime(year, month, 1).ToString("MMMM yyyy");
    }

    public string GetDateDisplayName(string yearAsString, string monthAsString, string dayAsString) {
      int year, month, day;
      GetDateParts(yearAsString, monthAsString, dayAsString, out year, out month, out day);
      return new DateTime(year, month, day).ToLongDateString();
    }

    private static int ConvertDatePart(string valueAsString, int defValue, int low, int high) {
      int value;
      if (string.IsNullOrEmpty(valueAsString) || !int.TryParse(valueAsString, out value))
        return defValue;
      if (low <= value && value <= high)
        return value;
      return defValue;
    }

    internal static void GetDateParts(string yearAsString, string monthAsString, out int year, out int month) {
      DateTime now = DateTime.Now;
      year = ConvertDatePart(yearAsString, now.Year, 1990, 2099);
      month = ConvertDatePart(monthAsString, now.Month, 1, 12);
    }

    private static void GetDateParts(string yearAsString, string monthAsString, string dayAsString, out int year, out int month, out int day) {
      DateTime now = DateTime.Now;
      year = ConvertDatePart(yearAsString, now.Year, 1990, 2099);
      month = ConvertDatePart(monthAsString, now.Month, 1, 12);
      day = ConvertDatePart(dayAsString, now.Day, 1, DateTime.DaysInMonth(year, month));
    }

    public static void ResetArchivePageStatistics() {
      GraffitiContext gc = GraffitiContext.Current;
      Post post = gc["post"] as Post;
      if ((post != null) && (string.Compare(post.Name, "archive", true)) == 0){
        PostStatistic.Destroy(PostStatistic.Columns.PostId, post.Id);
      }
    }
  }
}
